<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>楼层导航666</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    li {
      list-style: none;
    }

    section {
      height: 800px;
    }

    h1 {
      font-size: 45px;
      color: #fff;
      text-align: center;
      line-height: 800px;
    }

    #red {
      background: #73262e;
    }

    #orange {
      background: #8a582f;
    }

    #yellow {
      background: #8f912f;
    }

    #green {
      background: #216731;
    }

    #nav {
      position: fixed;
      border: 2px solid #eee;
      right: 50px;
      bottom: 80px;
    }

    #nav li {
      width: 120px;
      color: #fff;
      text-align: center;
      height: 50px;
      line-height: 50px;
      border-bottom: 2px solid rgba(238, 238, 238, 0.8);
    }

    #nav li:last-child {
      border: none;
    }

    #nav li.active {
      color: #000;
      background: rgba(238, 238, 238, 0.7);
    }
  </style>
</head>

<body>
  <section id="red">
    <h1>RED</h1>
  </section>
  <section id="orange">
    <h1>ORANGE</h1>
  </section>
  <section id="yellow">
    <h1>YELLOW</h1>
  </section>
  <section id="green">
    <h1>GREEN</h1>
  </section>

  <ul id="nav">
    <li class="active">RED</li>
    <li>ORANGE</li>
    <li>YELLOW</li>
    <li>GREEN</li>
  </ul>

  <script>
    const lis = document.querySelectorAll("#nav li")
    let currentIndex = 0

    // 点击导航滚动到相应的位置
    for (let i = 0; i < lis.length; i++) {
      lis[i].onclick = function () {
        currentIndex = i
        changActive()
        // 滚动到对应的色块
        window.scrollTo({
          top: 800 * i,
          behavior: 'smooth'
        })
      }
    }

    // 滚动切换nav  =>  根据当前滚动的位置获取应该激活的索引
    window.onscroll = function () {
      // console.log(window.scrollY);
      
      // 当滚出去一个色块的一半之后就算到了下一个色块（+400）
      let tempIndex = Math.floor((document.documentElement.scrollTop + 400) / 800)
      // 只有当要激活的索引变化了之后再执行切换激活样式的逻辑，节约dom操作提升性能
      if (currentIndex != tempIndex) {
        currentIndex = tempIndex
        changActive()
      }
    }

    function changActive() {
      // 给所有的元素清楚激活效果
      for (let i = 0; i < lis.length; i++) {
        lis[i].className = ''
      }
      // 给点击的元素加上激活效果
      lis[currentIndex].className = 'active'
    }

  </script>
</body>

</html>